package spring.cloud.tasks.tasks_assign_manager;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import spring.cloud.tasks.common.HostUtil;
import spring.cloud.tasks.tasks_assign_manager.schedule.ScheduleManager;
import spring.cloud.tasks.tasks_assign_manager.service.TaskItemAssignService;

import java.util.UUID;

@Slf4j
@Setter
@Getter
public class TasksManager {
    public TasksManagerConnectionStateListener tasksManagerConnectionStateListener;
    //
    public TaskItemAssignService taskItemAssignService;
    private String zooKeeperClusterKey;
    private String nameSpace;
    private CuratorFramework curatorFramework;
    private ScheduleManager scheduleManager;

    public TasksManager(CuratorFramework curatorFramework, String nameSpace) {
        this.nameSpace = nameSpace;
        this.curatorFramework = curatorFramework;


        this.taskItemAssignService = new TaskItemAssignService(curatorFramework, generateHostValue());
        this.scheduleManager = new ScheduleManager(nameSpace, curatorFramework, taskItemAssignService);

    }

    private String generateHostValue() {
        return HostUtil.cachedIpAddress + "-" + UUID.randomUUID();
    }

    /**
     * leadership election, add listeners
     */
    public void start() throws Exception {

        addConnectionLostListener();
        scheduleManager.start();
    }


    private void addConnectionLostListener() {
        tasksManagerConnectionStateListener = new TasksManagerConnectionStateListener(this, "connectionListener-for-nameSpaceSharding-" + nameSpace);
        curatorFramework.getConnectionStateListenable().addListener(tasksManagerConnectionStateListener);
    }

    //
    public void stopWithCuratorFramework() {
        stop();
        curatorFramework.close();

    }

    /**
     * close listeners, delete leadership
     */
    public void stop() {
        scheduleManager.stop();
        try {
            if (tasksManagerConnectionStateListener != null) {
                curatorFramework.getConnectionStateListenable().removeListener(tasksManagerConnectionStateListener);
                tasksManagerConnectionStateListener.shutdownNowUntilTerminated();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        try {
            taskItemAssignService.shutdown();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


}
